package org.fpp.jdk21study;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.LongAdder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Testcase
{
  private final ExecutorService blockingTasksExecutor = Executors.newVirtualThreadPerTaskExecutor();
  private final Logger log = LoggerFactory.getLogger(Testcase.class);

  public static void main(String[] args) throws InterruptedException
  {
    Testcase testcase = new Testcase();
    testcase.run();
  }

  public void run() throws InterruptedException
  {
    Semaphore semaphore = new Semaphore(5000);
    LongAdder adder = new LongAdder();
    while (true)
    {
      semaphore.acquire();
      blockingTasksExecutor.submit(() ->
      {
        try
        {
          for (int i = 0; i < 10_000; ++i)
          {
            adder.increment();
            long sum = adder.sum();
            if ((sum % 10_000) == 0)
              log.info("Progress: {}", sum);
            else
              log.debug("Progress: {}", sum);
          }
        }
        finally
        {
          semaphore.release();
        }
      });
    }
  }
}